package com.csw.android.dev_utils.ui.dialog

import android.app.Dialog
import android.content.Context
import android.content.DialogInterface
import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.LifecycleObserver
import androidx.lifecycle.OnLifecycleEvent

/**
 * 借助lifecycle实现页面销毁自动关闭对话框
 */
open class LifecycleDialog : Dialog, LifecycleObserver {
    /**
     * 设置lifecycle,如果是Fragment 应该使用viewLifecycleOwner.lifecycle
     */
    var lifecycle: Lifecycle? = null
        set(value) {
            if (field == value) {
                return
            }
            field?.removeObserver(this)
            field = value
            field?.addObserver(this)
        }

    constructor(context: Context) : super(context)
    constructor(context: Context, themeResId: Int) : super(context, themeResId)
    constructor(
        context: Context,
        cancelable: Boolean,
        cancelListener: DialogInterface.OnCancelListener?
    ) : super(context, cancelable, cancelListener)

    @OnLifecycleEvent(Lifecycle.Event.ON_DESTROY)
    fun onUIDestroy() {
        cancel()
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        /**
         * 通常上下文就是Activity，判断是否能直接用来获取lifecycle
         */
        val c = context
        if (c is ComponentActivity) {
            lifecycle = c.lifecycle
        }
    }
}